﻿using System;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Channels;
using CsCQ_Core.Extension;

namespace CsCQ_Core
{
    public class CqHelper
    {
        static CqHelper()
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = Path.GetFullPath(@"./");
            watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime;

            watcher.Changed += (sender, e) =>
            {
                AssemblyExtension.LoadAssembly(e.FullPath);
            };

            watcher.Created += (sender, e) =>
            {
                AssemblyExtension.LoadAssembly(e.FullPath);
            };

            watcher.Deleted += (sender, e) =>
            {
                AssemblyExtension.RemoveAssembly(e.FullPath);
            };

            watcher.EnableRaisingEvents = true;
        }

        public static void LoadLibs()
        {
            SetPrivatePath();
            AssemblyExtension.LoadAssemblys();
        }

        public static IGroupMessager[] GetMessagers()
        {
            var cqMessagers = AssemblyExtension.GetInstances<IGroupMessager>();
            return cqMessagers?.ToArray();
        }

        public static IPrivateMessager[] GetPrivateMessages()
        {
            var cqpm = AssemblyExtension.GetInstances<IPrivateMessager>();
            return cqpm?.ToArray();
        }

        public static IDiscussMessager[] GetDiscussMessager()
        {
            var cqdm = AssemblyExtension.GetInstances<IDiscussMessager>();
            return cqdm?.ToArray();
        }

        public static IStartup[] GetStartups()
        {
            return AssemblyExtension.GetInstances<IStartup>().ToArray();
        }

        public static void SetSdk(ICqSdk p_sdk)
        {
            CqSdk.SetSdk(p_sdk);
        }

        private static void SetPrivatePath()
        {
            var path = PathEx.Normal(@"cs\");
            AppDomain.CurrentDomain.AppendPrivatePath(path);

            //AppDomain.CurrentDomain.SetData("PRIVATE_BINPATH", path);
        }
    }
}